package cn.lyjuan.first.netty.demo._3_netty5.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Server
{
    public static void main(String[] args)
    {
        ServerBootstrap strap = new ServerBootstrap();

        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup(2);
        try
        {
            strap.group(boss, worker);

            // server channel factory
            strap.channel(NioServerSocketChannel.class);

            // channel pipeline factory
            strap.childHandler(new ChannelInitializer<Channel>()
            {
                protected void initChannel(Channel channel) throws Exception
                {
                    channel.pipeline().addLast(new StringDecoder());
                    channel.pipeline().addLast(new StringEncoder());
                    channel.pipeline().addLast(new ServerHandler());
                }
            });

            // options
            strap.option(ChannelOption.SO_BACKLOG, 2048);// server socket channel options
            strap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 20 * 1000);// socket channel options
            strap.childOption(ChannelOption.SO_KEEPALIVE, true);

            // listener
            ChannelFuture future = strap.bind(8000);
            System.out.println("server start");

            // wait for close
            future.channel().closeFuture().sync();
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        } finally
        {   // shutdown
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
